package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type Hobby struct {
	gorm.Model
	Name    string
	Peoples []People `gorm:"many2many:people_hobby"`
}
type People struct {
	gorm.Model
	Name   string
	Hobbys []Hobby `gorm:"many2many:people_hobby"`
}

func main() {
	db, err := gorm.Open("mysql", "root:123456@(127.0.0.1:3306)/gin?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()

	//自动迁移
	//方式1，先创建后关联
	//db.AutoMigrate(&Hobby{}, &People{})
	//db.Create(&Hobby{
	//	Model: gorm.Model{},
	//	Name:  "篮球",
	//})
	//db.Create(&Hobby{
	//	Model: gorm.Model{},
	//	Name:  "足球",
	//})
	//db.Create(&Hobby{
	//	Model: gorm.Model{},
	//	Name:  "乒乓球",
	//})
	//db.Create(&People{
	//	Model: gorm.Model{},
	//	Name:  "小明",
	//})
	//db.Create(&People{
	//	Model: gorm.Model{},
	//	Name:  "小王",
	//})
	//db.Create(&People{
	//	Model: gorm.Model{},
	//	Name:  "小张",
	//})
	//a := Hobby{}
	//db.First(&a)
	//
	//p := People{}
	//db.First(&p)
	//db.Model(&a).Association("Peoples").Append(&p)

	//方式2快捷方式
	basketball := Hobby{Name: "篮球"}
	football := Hobby{Name: "足球"}
	tableTennis := Hobby{Name: "乒乓球"}

	jack := People{Name: "杰克"}
	tom := People{Name: "汤姆"}
	mack := People{Name: "麦克"}

	jack.Hobbys = append(jack.Hobbys, basketball)
	tom.Hobbys = append(tom.Hobbys, basketball, football)
	mack.Hobbys = append(mack.Hobbys, tableTennis)

	db.Create(&jack)
	db.Create(&tom)
	db.Create(&mack)

}
